import router, { asyncRoutes } from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 在跳转之前获取用户资料
      if (!store.getters.name) {
        const res = await store.dispatch('user/actgetUserInfo')
        // 通过角色标识，过滤动态路由
        const canlook = asyncRoutes.filter(item => {
          return res.menus.includes(item.children[0].name)
        })
        // 存储菜单数据
        store.commit('menus/setMuneList', canlook)
        // console.log(res)
        router.addRoutes([...canlook, { path: '*', redirect: '/404', hidden: true }])
      }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
